package com.cn.service.Impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cn.response.Result;
import com.cn.utils.CategoryMenuTreeBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.mapper.CategoryMapper;
import com.cn.pojo.Category;
import com.cn.service.CategoryService;
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService{

    @Autowired
    private CategoryMapper categoryMapper;

    //已修改
    @Override
    public List<Category>  findMenuTree() {

        List<Category> rootMenu=this.baseMapper.selectList(null);
        List<Category> menuList= CategoryMenuTreeBuilder.build(rootMenu);
        return menuList;
    }

    @Override
    public List<Category> selectAllByName(String name) {
        return categoryMapper.selectAllByName(name);
    }

    @Override
    public Integer insert(Category category) {
      Category category1=this.baseMapper.selectById(category.getPid());
      if (category1.getLevel()==0){
          category.setLevel(1);
      }else  if (category1.getLevel()==1){
          category.setLevel(2);
      }else  if (category1.getLevel()==2){
          return 0;
      }
        return this.baseMapper.insert(category);
    }

    @Override
    public Category selectById(Long id) {
        return this.baseMapper.selectById(id);
    }


    @Override
    public Integer update(Category category) {
        Category category1=this.baseMapper.selectById(category.getPid());
         if (category.getId().equals(category.getPid())){
            return -1;
        }
        if (category1.getLevel()==0){
            category.setLevel(1);
        }else  if (category1.getLevel()==1){
            category.setLevel(2);
        }else  if (category1.getLevel()==2){
            return 0;
        }

        return this.baseMapper.updateById(category);
    }
    @Override
    public Integer delete(Long id) {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("pid",id);
        List<Category> categories = this.baseMapper.selectList(wrapper);
        for (int i = 0; i <categories.size(); i++) {
            System.err.println(categories.get(i).toString());
        }
        if (categories.size()>0){
            //THERE_ARE_DISHES_OR_CATEGORIES
/*            throw new BusinessException(ResultCode.THERE_ARE_DISHES_OR_CATEGORIES.getCode(),
                    ResultCode.THERE_ARE_DISHES_OR_CATEGORIES.getMessage());*/
            return 0;
        }else {
            return this.baseMapper.deleteById(id);

        }

    }
}
